const express = require("express");
const app = express();
const port = 443;

const moment = require("moment");
const path = require("path");

const https = require("https");
const fs = require("fs");
const httpsOption = {
  key: fs.readFileSync("./ssl/a.key"),
  cert: fs.readFileSync("./ssl/a.crt"),
};
const server = https.createServer(httpsOption, app);

app.use('/public',express.static('public'))

// 允许跨域
app.all("*", function (req, res, next) {
  console.log(req.headers.origin);
  console.log(req.environ);
  res.header("Access-Control-Allow-Origin", req.headers.origin);
  // res.header("Access-Control-Allow-Origin", '*');
  res.header(
    "Access-Control-Allow-Headers",
    "Content-Type,Content-Length, Authorization, Accept,X-Requested-With"
  );
  res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  res.header("Access-Control-Allow-Credentials", "true");
  res.header("X-Powered-By", " 3.2.1");
  if (req.method === "OPTIONS") res.send(200); /*让options请求快速返回*/
  else next();
});

// multer使用
//1需安装npm i multer
const multer = require("multer");
const mkdirp = require("mkdirp");
//2初始化中间件并设置上传目录
// const upload = multer({ dest: 'uploads/' })
const storage = multer.diskStorage({
  destination: async (req, file, cb) => {
    //自定义动态存储目录：譬如按日期
    //每天一个目录保存上传文件
    const day = moment().format("YYYYMMDD"); //使用moment需要npm i moment
    //组装路径uploads\20210109
    const dir = path.join("uploads", day);
    //异步创建多级目录
    await mkdirp(dir); //使用mkdirp（创建多级目录）需要npm i mkdirp
    cb(null, dir);
  },
  filename: (req, file, cb) => {
    //获取文件后缀
    let extname;
    if (file.originalname === "blob") {
      switch (file.mimetype) {
        case "application/zip":
          extname = ".zip";
          break;
      }
    } else {
      extname = path.extname(file.originalname);
    }
    const uniqueSuffix =
      Date.now() + "-" + Math.round(Math.random() * 1e9) + extname;
    cb(null, file.fieldname + "-" + uniqueSuffix);
  },
});
const upload = multer({ storage: storage });

app.get("/", (req, res) => res.send("hello world22!"));
//3添加到需要上传一个name属性为pic的单文件上传路由：upload调用single方法传入需上传文件的name属性
app.post("/upfile", upload.single("pic"), (req, res) => {
  //4返回信息：自此文件已经上传到了upload目录，文件是一个随机的没有文件后缀的文件
  res.send({
    //post上传的文件信息（单个文件，当使用single方法时）
    file: req.file,
    //post提交的其他数据
    body: req.body,
  });
});
//4添加到需要上传一个name属性为pic的单文件上传路由：upload调用single方法传入需上传文件的name属性
app.post("/upfiles", upload.array("pics", 12), (req, res) => {
  res.send({
    // //post上传的文件信息（多个文件,当使用array方法传入name属性pics及最大上传文件数目12）
    files: req.files,
    //post提交的其他数据
    body: req.body,
  });
});

server.listen(port, () => console.log(`app listening on port of ${port}`));
